package com.yzdbx.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

import static com.yzdbx.utils.DbUtil.getMaxId;
import static com.yzdbx.utils.GenUtil.CUR_DATE;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class PointInspectionTaskRunnable implements Exe {


    private Connection connection;

    private static Map<String, List<Map<String, String>>> handlingMap = new LinkedHashMap<>();

    static {
        // 1. 外观结构异常处理
        handlingMap.put("设备外观及结构检查", Arrays.asList(new HashMap<>() {{
            put("机架严重变形", "立即停机并悬挂警示牌，通知结构工程师评估");
        }}, new HashMap<>() {{
            put("防护罩断裂", "移除破损部件并安装临时防护网");
        }}, new HashMap<>() {{
            put("地脚螺栓断裂", "使用液压千斤顶支撑设备后更换螺栓");
        }}, new HashMap<>() {{
            put("焊接部位开裂", "打磨裂纹末端止裂孔并临时加固");
        }}, new HashMap<>() {{
            put("腐蚀穿孔", "刮除锈蚀层后使用金属修补剂填补");
        }}));

        // 2. 运行参数异常处理
        handlingMap.put("运行参数检测", Arrays.asList(new HashMap<>() {{
            put("轴承温度超标", "紧急停机后检查润滑系统并强制冷却");
        }}, new HashMap<>() {{
            put("振动值超限", "加装临时减震垫并安排动平衡校正");
        }}, new HashMap<>() {{
            put("电流波动异常", "断开电源检查电机绕组绝缘情况");
        }}, new HashMap<>() {{
            put("异响持续", "拆解传动部件检查齿轮啮合状态");
        }}, new HashMap<>() {{
            put("转速不稳定", "检查变频器参数并更换编码器");
        }}));

        // 3. 润滑系统异常处理
        handlingMap.put("润滑系统检查", Arrays.asList(new HashMap<>() {{
            put("油管爆裂", "关闭油路阀门并更换耐高压软管");
        }}, new HashMap<>() {{
            put("润滑油乳化", "排空油箱并使用煤油冲洗系统");
        }}, new HashMap<>() {{
            put("自动注油失效", "切换手动模式并更换堵塞滤芯");
        }}, new HashMap<>() {{
            put("轴承缺油烧结", "拆除损坏轴承并清理轴颈表面");
        }}, new HashMap<>() {{
            put("油位异常下降", "检查密封件并补充同型号润滑油");
        }}));

        // 4. 安全装置异常处理
        handlingMap.put("安全防护测试", Arrays.asList(new HashMap<>() {{
            put("急停按钮卡死", "拆除面板并更换微动开关组件");
        }}, new HashMap<>() {{
            put("光栅误动作", "调整光学镜头焦距并清洁感应面");
        }}, new HashMap<>() {{
            put("联锁失效", "短接安全回路并张贴强制运行警示");
        }}, new HashMap<>() {{
            put("过载保护未触发", "手动测试脱扣机构并校准电流继电器");
        }}, new HashMap<>() {{
            put("安全门变形", "使用角磨机修整门框并更换密封条");
        }}));

        // 5. 电气系统异常处理
        handlingMap.put("电气线路检查", Arrays.asList(new HashMap<>() {{
            put("电缆过热", "剪除烧损段并压接新电缆接头");
        }}, new HashMap<>() {{
            put("接触器粘连", "拆解触点组件并用砂纸打磨平整");
        }}, new HashMap<>() {{
            put("绝缘击穿", "包裹三层绝缘胶带并安排线槽改造");
        }}, new HashMap<>() {{
            put("PLC模块故障", "热插拔更换备用模块并下载程序");
        }}, new HashMap<>() {{
            put("接地不良", "开挖基础重新敷设镀锌接地极");
        }}));

        // 6. 仪表校准异常处理
        handlingMap.put("仪表参数校准", Arrays.asList(new HashMap<>() {{
            put("压力表指针卡滞", "轻敲表壳释放压力后送检校验");
        }}, new HashMap<>() {{
            put("温度显示漂移", "冰水混合物中重置传感器零点");
        }}, new HashMap<>() {{
            put("流量计积垢", "拆解转子组件并用超声波清洗");
        }}, new HashMap<>() {{
            put("速度传感器失效", "调整感应间隙至1.5mm标准值");
        }}, new HashMap<>() {{
            put("数显表乱码", "断电复位并更换后备电池");
        }}));

        // 7. 紧固件异常处理
        handlingMap.put("紧固件状态确认", Arrays.asList(new HashMap<>() {{
            put("地脚螺栓松动", "使用液压扳手按对角线顺序紧固");
        }}, new HashMap<>() {{
            put("皮带打滑", "调整张紧轮并涂抹防滑涂层");
        }}, new HashMap<>() {{
            put("链条跳齿", "截除两节链节并更换连接销");
        }}, new HashMap<>() {{
            put("联轴器偏移", "松开底座螺栓重新激光对中");
        }}, new HashMap<>() {{
            put("螺纹滑牙", "攻丝加大规格并更换高强度螺栓");
        }}));

        // 8. 流体系统异常处理
        handlingMap.put("气动液压检测", Arrays.asList(new HashMap<>() {{
            put("气缸内漏", "更换活塞密封圈并测试保压性能");
        }}, new HashMap<>() {{
            put("液压油泡沫化", "静置24小时后排气并更换滤网");
        }}, new HashMap<>() {{
            put("快速接头漏气", "剪除破损O型圈并涂抹硅脂");
        }}, new HashMap<>() {{
            put("蓄能器失效", "释放氮气后重新充压至额定值");
        }}, new HashMap<>() {{
            put("电磁阀卡涩", "拆解阀芯并用煤油清洗杂质");
        }}));

        // 9. 清洁维护异常处理
        handlingMap.put("清洁维护作业", Arrays.asList(new HashMap<>() {{
            put("粉尘爆炸风险", "湿式清理后安装防爆型吸尘装置");
        }}, new HashMap<>() {{
            put("油泥堆积", "使用环保型清洗剂高压冲洗");
        }}, new HashMap<>() {{
            put("散热片堵塞", "压缩空气反向吹扫并校正翅片");
        }}, new HashMap<>() {{
            put("电路板积碳", "无水酒精擦拭后涂覆三防漆");
        }}, new HashMap<>() {{
            put("滤网破损", "双层临时滤布包扎并订购原厂件");
        }}));

        // 10. 数据记录异常处理
        handlingMap.put("运行数据记录", Arrays.asList(new HashMap<>() {{
            put("数据丢失", "从备份服务器恢复最近时间点数据");
        }}, new HashMap<>() {{
            put("传感器断线", "短接测试线路并更换航空插头");
        }}, new HashMap<>() {{
            put("系统时间错误", "同步NTP服务器并校准RTC时钟");
        }}, new HashMap<>() {{
            put("通讯中断", "检查RS485终端电阻并重启网关");
        }}, new HashMap<>() {{
            put("存储卡满", "导出历史数据后格式化分区");
        }}));
    }

    public PointInspectionTaskRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) throws SQLException {
        LocalDate localDate = CUR_DATE.get();

        PreparedStatement statement = connection.prepareStatement("select * from djpointInspectionProgramme");
        ResultSet resultSet = statement.executeQuery();
        List<LinkedHashMap<String, Object>> resultSetToList = DbUtil.resultSetToList(resultSet);

        if (CollectionUtil.isEmpty(resultSetToList)) {
            //初始化计划
            statement = connection.prepareStatement("select * from equipmentCounterStatements");
            List<LinkedHashMap<String, Object>> shebeiList = DbUtil.resultSetToList(statement.executeQuery());
            int id = 1;
            for (LinkedHashMap<String, Object> shebei : shebeiList) {
                statement = connection.prepareStatement("insert into djpointInspectionProgramme(id,dotCheckPlanNumber,fff3,deviceName,checkFrequency,checkOutThePersonResponsible,otherOrganiser,numberOfChecksConducted,status,inspector)values (?,?,?,?,?,?,?,?,?,?)");
                statement.setInt(1, id++);
                statement.setString(2, GenUtil.getNoFromTable(connection,"DJ-","djpointInspectionProgramme", "dotCheckPlanNumber"));
                statement.setString(3, shebei.get("f65e").toString() + "日常点检");
                statement.setString(4, shebei.get("f65e").toString());
                statement.setString(5, "每日");
                statement.setString(6, shebei.get("responsiblePersons").toString());
                String key = RandomUtil.randomEle(handlingMap.keySet().toArray(new String[0]));
                statement.setString(7, key);
                statement.setBigDecimal(8, BigDecimal.ONE);
                statement.setString(9, "启用");
                statement.setString(10, shebei.get("responsiblePersons").toString());
                statement.execute();
            }

            statement = connection.prepareStatement("select * from djpointInspectionProgramme");
            resultSetToList = DbUtil.resultSetToList(statement.executeQuery());
        }

        if (CollectionUtil.isEmpty(resultSetToList)) return Boolean.TRUE;

        int id = getMaxId(connection, "sbdjpilotTasksheet");
        int num = 0;
        //点检任务开始时间递增 8------>

        for (LinkedHashMap<String, Object> map : resultSetToList) {
            long start = localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli() + 1000 * 60 * 60 * 6 + RandomUtil.randomLong(60000, 3600000);
            //查询到维保任务
            statement = connection.prepareStatement("insert into sbdjpilotTasksheet(id,checklistNumbering1,checklistName,deviceName,checkpointStatus,checkOutThePersonResponsible,plannedStartDate,plannedEndDate,otherOrganiser,ffac,numberOfEquipment,checkinaberrations,pointCheckGenerationTime,otherOrganiser1) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            statement.setInt(1, ++id);
            statement.setString(2, GenUtil.getNoFromTable(connection,"DJRW","sbdjpilotTasksheet", "checklistNumbering1"));
            statement.setString(3, map.get("fff3").toString());
            statement.setString(4, map.get("deviceName").toString());
            statement.setString(6, map.get("checkOutThePersonResponsible").toString());
            statement.setDate(7, Date.valueOf(localDate));
            statement.setDate(8, Date.valueOf(localDate));
            Timestamp end = new Timestamp(start + 1000 * 60 * 60 * 8);
            String state = System.currentTimeMillis() > end.getTime() ? "已完成" : "待点检";
            statement.setTimestamp(9, new Timestamp(start));
            statement.setTimestamp(10, System.currentTimeMillis() > end.getTime() ? end : null);
            statement.setString(5, state);
            statement.setBigDecimal(11, BigDecimal.ONE);
            int ycSl = "已完成".equals(state) ? RandomUtil.randomInt(0, 6) : 0;
            statement.setBigDecimal(12, BigDecimal.valueOf(ycSl));
            statement.setTimestamp(13, new Timestamp(start - RandomUtil.randomLong(1000 * 60 * 60)));
            statement.setString(14, map.get("otherOrganiser").toString());
            statement.execute();

            statement = connection.prepareStatement("update djpointInspectionProgramme set numberOfChecksConducted = numberOfChecksConducted +?  where id =?");
            statement.setInt(1, 1);
            statement.setString(2, map.get("id").toString());
            statement.execute();

            List<Map<String, String>> items = handlingMap.get(map.get("otherOrganiser").toString());
            //获取标记为异常的点检项
            int maxId = getMaxId(connection, "sbdj04PointBreakdown");
            List<Integer> ycIndexList = getYcIndex(items.size(), ycSl);
            for (int i = 0; i < items.size(); i++) {
                statement = connection.prepareStatement("insert into sbdj04PointBreakdown(id,deviceNumber1,queuedResults,anomalousDescription,measuresToAddressThem,otherOrganiser1) values (?,?,?,?,?,?)");
                statement.setInt(1, ++maxId);
                statement.setString(2, map.get("deviceName").toString());
                String key = items.get(i).keySet().toArray(new String[0])[0];
                statement.setString(3, ycIndexList.contains(i) ? "异常" : "正常");
                statement.setString(4, key);
                statement.setString(5, ycIndexList.contains(i) ? items.get(i).get(key) : "无");
                statement.setInt(6, id);
                statement.execute();
            }
        }
        //更新点检状态
        statement = connection.prepareStatement("select * from sbdjpilotTasksheet where ffac < ? and checkpointStatus!=?");
        statement.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now()));
        statement.setString(2, "已完成");
        resultSetToList = DbUtil.resultSetToList(statement.executeQuery());

        for (LinkedHashMap<String, Object> map : resultSetToList) {
            statement = connection.prepareStatement("update sbdjpilotTasksheet set checkpointStatus = ? ,ffac=? ,itsTimeconsuming=? where id = ?");
            statement.setString(1, "已完成");
            long tmp = RandomUtil.randomLong(3);
            statement.setTimestamp(2, new Timestamp(((Timestamp) map.get("otherOrganiser")).getTime() + 1000 * 60 * 60 * tmp));
            statement.setInt(3, ((int) tmp));
            statement.setString(4, map.get("id").toString());
            statement.execute();
        }
        return Boolean.TRUE;
    }

    private List<Integer> getYcIndex(int size, int yc) {
        Set<Integer> r = new HashSet<>();
        if (RandomUtil.randomInt(10) < 9)
            return new ArrayList<>();
        while (r.size() < yc) {
            r.add(RandomUtil.randomInt(0, size));
        }
        return new ArrayList<>(r);
    }


    public static void main(String[] args) {
        LocalDate start = MainTask.start;
        LocalDate end = MainTask.end;
        Connection conn = null;
        try {
            conn = DbUtil.getConnection();
            while (!start.isAfter(end)) {
                CUR_DATE.set(start);
                PointInspectionTaskRunnable maintenanceTaskRunnable = new PointInspectionTaskRunnable(conn);
                maintenanceTaskRunnable.execute(0);

                start = start.plusDays(1);
            }
            conn.commit();

        } catch (Exception ex) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } finally {
            DbUtil.closeConnection(conn);
        }
    }



}
